import { showFailToast, showSuccessToast } from 'vant';
import { ref } from 'vue';

import { addCardByBatch, addCardBySingle } from '../api';
import { CardSubmitType } from '../const';
import CardConfig from '../models/CardConfig';

const useCardConfig = () => {
  const loading = ref(false);
  const cardConfig = ref(new CardConfig());

  const form = ref({
    validate: () => Promise.resolve(),
  });
  const handleAdd = async () => {
    try {
      loading.value = true;
      await form.value.validate();
      if (cardConfig.value.submitType === CardSubmitType.Single) {
        const { data } = await addCardBySingle(cardConfig.value);
        showSuccessToast(data.msg || '提交成功，等待核验');
      } else if (cardConfig.value.submitType === CardSubmitType.Multiple) {
        const { data } = await addCardByBatch(cardConfig.value);
        showSuccessToast(data.msg || '批量提交成功，等待核验');
      } else if (cardConfig.value.submitType === CardSubmitType.Empty) {
        showFailToast('该卡不可用');
      }
    } catch (error) {
      //
    } finally {
      loading.value = false;
    }
  };
  return {
    cardConfig,
    loading,
    form,
    handleAdd,
  };
};

export default useCardConfig;
